from SelectionBuffer import SelectionBuffer
import Console
from scipy import optimize
import LineDraw

__author__ = 'Hugh Owens - Mycroftholmeslives@gmail.com'
__version__ = '0.1F'

from GameStateManager import *
import GameEngine
import ogre.renderer.OGRE as ogre
import ogre.gui.CEGUI as CEGUI
import ogre.io.OIS as OIS


    


class PlayState(GameState):

    __metaclass__ = Singleton

    def enter(self):
        self.root = ogre.Root.getSingleton()
        self.sceneManager = self.root.createSceneManager(ogre.ST_GENERIC)
        self.renderer = CEGUI.OgreRenderer.bootstrapSystem()
        self.system = CEGUI.System.getSingleton()
        self.meshManager = ogre.MeshManager.getSingleton()

        self.initGameEngine()

        self.initConsole()
        self.initCamera()
        self.initWorld()
        self.initStateVars()

    def initGameEngine(self):
        self.engine = GameEngine.getNewEngine()


    def initConsole(self):
        self.console = Console.Console(self.root,self)
        self.console.addLocals({'root':self.root})
        self.consoleDown = False

    def initCamera(self):
        self.camera = self.sceneManager.createCamera("PlayCamera")
        self.camera.position = (0, 450, -50)
        self.camera.lookAt (0, 0, 0)
        self.camera.nearClipDistance = 5
        self.camMoveSpeed = 50
        self.camRotateSpeed = 1/100.0

        self.viewport = self.root.getAutoCreatedWindow().addViewport(self.camera)
        self.viewport.setBackgroundColour(ogre.ColourValue(0.0, 0.0, 1.0))
        self.selectionBuffer = SelectionBuffer(self.sceneManager, self.root.getRenderTarget("GameWindow"))

        CEGUI.SchemeManager.getSingleton().create("TaharezLookSkin.scheme")
        CEGUI.MouseCursor.getSingleton().setImage("TaharezLook", "MouseArrow")
        self.system.setDefaultMouseCursor("TaharezLook", "MouseArrow")
        self.system.setDefaultFont("BlueHighway-12")


    def initWorld(self):
        self.sceneManager.setSkyBox(True,"HiResSkyBox")

        # Setup a mesh object.
        #ent = self.sceneManager.createEntity('Ninja', \
        #    .convertToMesh())
        #manobj = LineDraw.createUserQuad(self.sceneManager,'q',"mycube",[(0,0,0),(10,0,0),(10,10,0),(0,10,0)])
        #self.sceneManager.getRootSceneNode().createChildSceneNode('q').attachObject(manobj)
        #self.sceneManager.getSceneNode('Ninja').showBoundingBox(True)
        #self.sceneManager.getSceneNode('q').setPosition(50,50,0)

        ent = self.sceneManager.createEntity('obj','mycube.mesh')
        self.sceneManager.getRootSceneNode().createChildSceneNode('obj').attachObject(ent)
        self.clickPlane = None

    def initStateVars(self):

        ###self.t_0 = GET CURRENT TIME
        ###self.delta_t = 0

        self.ExitGame = False
        self.paused = False
        self.leftMouseDown = False
        self.rightMouseDown = False
        self.currentObject = None
        self.clickState = "Selection"
        self.selected = None
        self.downPos = None


    def exit(self):
        self.sceneManager.clearScene()
        self.sceneManager.destroyAllCameras()
        self.root.getAutoCreatedWindow().removeAllViewports()

    def resume(self):
        self.viewport.setBackgroundColour(ogre.ColourValue(0.0, 0.0, 1.0))

    def keyPressed(self, evt):
        if evt.key == OIS.KC_ESCAPE:
            if self.consoleDown:
                self.console.hide()
            else:
                self.ExitGame = True
        else:
            self.console.keyPressed(evt)
                

    def mouseMoved(self, evt):
        CEGUI.System.getSingleton().injectMouseMove(evt.get_state().X.rel, evt.get_state().Y.rel)
        if self.rightMouseDown:
            self.camera.yaw(ogre.Degree(-evt.get_state().X.rel * self.camRotateSpeed))
            self.camera.pitch(ogre.Degree(-evt.get_state().Y.rel * self.camRotateSpeed))
        return True

    def mousePressed(self, evt, id):
        if id == OIS.MB_Left:
            self.onLeftPressed(evt)
            self.leftMouseDown = True

        elif id == OIS.MB_Right:
            CEGUI.MouseCursor.getSingleton().hide()
            self.rightMouseDown = True
        return True

    def mouseReleased(self, evt, id):
        if id == OIS.MB_Left:
            self.onLeftReleased(evt)
        elif id == OIS.MB_Right:
            CEGUI.MouseCursor.getSingleton().show()
            self.rightMouseDown = False
        return True

    def onLeftPressed(self, evt):
        if self.clickState == "Selection":
            clicked = self.getClicked()
            if clicked != None and clicked.getName() == "obj":
                self.selected = clicked
                self.clickState = "Position"
                if self.clickPlane == None:
                    self.clickPlaneMath = ogre.Plane ((0, 1, 0), 0)
                    self.meshManager.createPlane ('ClickPlane', 'General', self.clickPlaneMath,
                                     1500, 1500, 20, 20, True, 1, 5, 5, (0, 0, 1))
                    self.clickPlane = self.sceneManager.createEntity('cp', 'ClickPlane')
                    self.sceneManager.getRootSceneNode().createChildSceneNode ('cp_n').attachObject (self.clickPlane)
                    self.clickPlane.setMaterialName ('Examples/Rockwall')
                    self.clickPlane.castShadows = False


        elif self.clickState == "Position":
            print "Clicked for position";
            self.mouseDownPos = self.getMousePos()
            print self.mouseDownPos
            self.clickState = "Velocity"
        elif self.clickState == "Velocity":
            raise RuntimeError, "Something went awry. clickState should have been cleared."


    def onLeftReleased(self, evt):

        if self.clickState == "Velocity":
            print "Released for velocity"
            self.velVector = self.getMousePos() - self.mouseDownPos
            print self.velVector
            self.clickState = "Selection"
            




    def getClicked(self):
        print "Clicked"
        mousePos = CEGUI.MouseCursor.getSingleton().getPosition()
        screenX = mousePos.d_x
        screenY = mousePos.d_y
        #print screenX,screenY
        ent = self.selectionBuffer.onSelectionClick(screenX, screenY)
        print ent
        if ent != None:
            print ent.getName()
        return ent

    def frameStarted(self, evt):

        ###self.delta_t = GET CURRENT TIME - self.t_0
        ###self.t_0 = self.t_0 + self.delta_t

        self.engine.tick()

        #if not self.paused:
        #    self.sceneManager.getSceneNode('obj').translate(.001,.001,.001)
        return True

    def frameEnded(self, evt):
        return not self.ExitGame

    def getMousePos(self):
        mousePos = CEGUI.MouseCursor.getSingleton().getPosition()
        mouseRay = self.camera.getCameraToViewportRay(mousePos.d_x,mousePos.d_y)
        intersection = mouseRay.intersects(ogre.Plane((0,1,0),int(self.selected.getParentSceneNode().position.y)))

        d = intersection.second

        print d

        point = mouseRay.getPoint(d)

        return point


if __name__ == "__main__":
    game = GameManager()
    game.start(PlayState)